import bankCardApi from '@/api/modules/bankCard';
import { useBankCardStore } from '@/store';

/**
 * 银行卡服务 - 处理银行卡相关的业务逻辑和API调用
 */
class BankService {
  constructor() {
    this.bankCardStore = useBankCardStore();
  }

  /**
   * 获取用户银行卡列表
   * @param {Number} userId 用户ID
   * @returns {Promise<Array>} 银行卡列表
   */
  async getBankCards(userId) {
    try {
      const response = await bankCardApi.getList(userId);
      // 更新store中的银行卡列表
      this.bankCardStore.setBankCards(response);
      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取银行卡详情
   * @param {Number} id 银行卡ID
   * @returns {Promise<Object>} 银行卡详情
   */
  async getBankCardDetail(id) {
    try {
      const response = await bankCardApi.getDetail(id);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 添加银行卡
   * @param {Object} bankCardData 银行卡数据
   * @returns {Promise<Object>} 添加结果
   */
  async addBankCard(bankCardData) {
    try {
        const response = await bankCardApi.add(bankCardData);
        await this.getBankCards(bankCardData.userId);
        return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 更新银行卡
   * @param {Object} bankCardData 银行卡数据
   * @returns {Promise<Object>} 更新结果
   */
  async updateBankCard(bankCardData) {
    try {
        const response = await bankCardApi.update(bankCardData);
        await this.getBankCards(bankCardData.userId);
        return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 删除银行卡
   * @param {Number} id 银行卡ID
   * @param {Number} userId 用户ID
   * @returns {Promise<Object>} 删除结果
   */
  async deleteBankCard(id, userId) {
    try {
      const response = await bankCardApi.delete(id);
      await this.getBankCards(userId);
      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 设置默认银行卡
   * @param {Number} id 银行卡ID
   * @param {Number} userId 用户ID
   * @returns {Promise<Object>} 设置结果
   */
  async setDefaultBankCard(id, userId) {
    try {
      const response = await bankCardApi.setDefault(id, userId);
      await this.getBankCards(userId);
      return response;
    } catch (error) {
      throw error;
    }
  }
}

// 导出单例
export default new BankService();